package com.proj.android.canyondefense.core.impl;

import java.util.ArrayList;
import java.util.List;

import android.view.MotionEvent;
import android.view.View;

import com.proj.android.canyondefense.core.base.IInput.TouchEvent;
import com.proj.android.canyondefense.core.base.ITouchHandler;
import com.proj.android.canyondefense.core.base.Pool;
import com.proj.android.canyondefense.core.base.Pool.IPoolObjectFactory;

public class SingleTouchHandler implements ITouchHandler {

	private boolean _isTouched;
	private int _touchX;
	private int _touchY;
	private float _scaleX;
	private float _scaleY;
	private List<TouchEvent> _touchEvents = new ArrayList<TouchEvent>();
	private List<TouchEvent> _touchEventsBuffer = new ArrayList<TouchEvent>();
	private Pool<TouchEvent> _touchEventPool;
	
	public SingleTouchHandler(View view, float scaleX, float scaleY) {
		IPoolObjectFactory<TouchEvent> factory = new IPoolObjectFactory<TouchEvent>() {
			public TouchEvent createObject() {
				return new TouchEvent();
			}
			
		};
		
		_touchEventPool = new Pool<TouchEvent>(factory, 100);
		view.setOnTouchListener(this);
		this._scaleX = scaleX;
		this._scaleY = scaleY;
	}

	public boolean onTouch(View v, MotionEvent event) {
		synchronized (this) {
			TouchEvent touchEvent = _touchEventPool.newObject();
			switch (event.getAction()) {
				case MotionEvent.ACTION_DOWN:
	                touchEvent.type = TouchEvent.TOUCH_DOWN;
	                _isTouched = true;
	                break;
	            case MotionEvent.ACTION_MOVE:
	                touchEvent.type = TouchEvent.TOUCH_DRAGGED;
	                _isTouched = true;
	                break;
	            case MotionEvent.ACTION_CANCEL:                
	            case MotionEvent.ACTION_UP:
	                touchEvent.type = TouchEvent.TOUCH_UP;
	                _isTouched = false;
	                break;
			}
			touchEvent.x = _touchX = (int)(event.getX() * _scaleX);
            touchEvent.y = _touchY = (int)(event.getY() * _scaleY);
            _touchEventsBuffer.add(touchEvent);
            return true;
		}
	}

	public boolean isTouchDown(int pointer) {
		synchronized (this) {
			if (pointer == 0) {
				return _isTouched;
			} else {
				return false;
			}
		}
	}

	public int getTouchX(int pointer) {
		synchronized (this) {
			return _touchX;
		}
	}

	public int getTouchY(int pointer) {
		synchronized (this) { 
			return _touchY;
			
		}
	}

	public List<TouchEvent> getTouchEvents() {
		synchronized (this) {
			int len = _touchEvents.size();
			for (int i = 0; i < len; i++) {
				_touchEventPool.free(_touchEvents.get(i));
			}
			_touchEvents.clear();
			_touchEvents.addAll(_touchEventsBuffer);
			_touchEvents.clear();
	        return _touchEvents;
		}
	}

}
